<?php
/**
 * Created by PhpStorm.
 * User: TC
 * Date: 2016/3/28
 * Time: 16:07
 */
require_once dirname(__FILE__) . '/../libs/controller/JoinController.php';
require_once dirname(__FILE__) . '/../Config.php';

$join = new join();
$join->Router();

class join
{
  public function Router()
  {
    /*
     * 路由
     */
    $action = isset($_GET[Constant::ACTION_FIELD]) ? $_GET[Constant::ACTION_FIELD] : '';
    switch ($action) {
      case 'add':
        //添加加盟信息
        $this->AddJoinMsg();
        break;
      case 'list':
        //获取加盟信息列表
        $this->GetJoinList();
        break;
      default:
        ResponseMsg::ResponseErrorMsg(404);
        break;
    }
  }

  /*
   * 添加加盟信息
   */
  private function AddJoinMsg()
  {
    if ($_SERVER['REQUEST_METHOD'] != 'POST') {
      ResponseMsg::ResponseErrorMsg(404);
      return;
    }
    $data = Util::TranInputData();
    if (!isset($data[JoinModel::TEL_FIELD]) || (!$data[JoinModel::TEL_FIELD])) {
      ResponseMsg::ResponseErrorMsg(400, '缺少电话号码');
      return;
    }
    if (!isset($data[JoinModel::NAME_FIELD]) || (!$data[JoinModel::NAME_FIELD])) {
      ResponseMsg::ResponseErrorMsg(400, '缺少电话号码');
      return;
    }
    if (!isset($data[JoinModel::PROVINCE_FIELD]) || (!$data[JoinModel::PROVINCE_FIELD])) {
      ResponseMsg::ResponseErrorMsg(400, '缺少电话号码');
      return;
    }
    if (!isset($data[JoinModel::CITY_FIELD]) || (!$data[JoinModel::CITY_FIELD])) {
      ResponseMsg::ResponseErrorMsg(400, '缺少电话号码');
      return;
    }
    $tel = $data[JoinModel::TEL_FIELD];
    if (JoinController::CheckTel($tel)) {
      ResponseMsg::ResponseErrorMsg(400, '该手机号已经添加过加盟信息');
      return;
    }
    $name = $data[JoinModel::NAME_FIELD];
    $province = $data[JoinModel::PROVINCE_FIELD];
    $city = $data[JoinModel::CITY_FIELD];
    $ext = isset($data[JoinModel::EXT_FIELD])?$data[JoinModel::EXT_FIELD]:'';
    $lastId = JoinController::AddJoin($tel, $name, $province, $city, $ext);
    $msgArr = $lastId > 0 ? [200, '添加成功'] : [400, '添加失败'];
    ResponseMsg::ResponseErrorMsgArr($msgArr);
    return;
  }

  /*
   * 获取列表
   */
  private function GetJoinList()
  {
    if ($_SERVER['REQUEST_METHOD'] != 'GET') {
      ResponseMsg::ResponseErrorMsg(404);
      return;
    }
    $page = isset($_GET[Constant::PAGE_FIELD]) ? $_GET[Constant::PAGE_FIELD] : 1;
    $joinList = JoinController::JoinList($page);
    ResponseMsg::ResponseContent(['data' => $joinList, 'page' => $page], 'success');
    return;
  }
}